package deng.spring.userwebapp.services.spring;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import deng.spring.userwebapp.dal.CrudDao;

/**
 * A CrudDao base class that uses Spring HibernateTemplate, and to provide subclass with all the Spring's 
 * infrastructure support.
 * 
 * @author Zemian
 *
 * @param <E>
 * @param <K>
 */
public abstract class AbstractHibernateCrudDao<E, K extends Serializable> extends HibernateDaoSupport implements CrudDao<E, K> {
	
	private Class<E> entityClass;
	public Class<E> getEntityClass() {
		return entityClass;
	}

	public AbstractHibernateCrudDao() {
		// Get the class object from the entity generic type parameter
		Type entityType = ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		@SuppressWarnings("unchecked")
		Class<E> entityTypeClass = (Class<E>)entityType;
		this.entityClass = entityTypeClass;
	}
	
	@Override
	public void create(E entity) {
		getHibernateTemplate().persist(entity);
	}
	
	@Override	
	public E read(K key) {
		return getHibernateTemplate().get(entityClass, key);
	}

	@Override
	public void update(E entity) {
		getHibernateTemplate().update(entity);
	}

	@Override
	public void delete(K key) {
		HibernateTemplate ht = getHibernateTemplate();
		E entity = ht.load(entityClass, key);
		ht.delete(entity);
	}

}
